//
//  LimitFreeViewController.swift
//  1604_LimitFree
//
//  Created by 千锋 on 16/9/26.
//  Copyright © 2016年 Mabin. All rights reserved.
//

import UIKit

class LimitFreeViewController: LFBaseViewController {

   
    //分类的类型
    private var cateId : String?
    
    override func viewDidLoad() {
        super.viewDidLoad()

         self.view.backgroundColor = UIColor.orangeColor()
        
        //导航
//        createMyNav()
        
        //创建表格
//        createTableView()
        
        //分页上拉刷新下拉加载
        addRedresh()
        
        //下载方法
//        downloaderData()
        
    }
    
    //创建导航的部分
    override func createMyNav()
    {
        //分类按钮
        addNavBarbutton("分类", target: self, action: "gotoCategory", isLeft: true)
        
        //标题
        addnavTitle("限免")
        
        //设置按钮
        addNavBarbutton("设置", target:self , action: "gotoSetPage", isLeft: false)
    }
    
    //分类的页面
    func gotoCategory()
    {
        let cateVC = CategoryViewController()
        
        //类型的值
        cateVC.type = .LimitFree
        
        //设置代理
        cateVC.delegate = self
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(cateVC, animated: true)
        self.hidesBottomBarWhenPushed = false
    }
    
    //设置的页面
    func gotoSetPage()
    {
        let setVc = SettingViewController()
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(setVc, animated: true)
        self.hidesBottomBarWhenPushed = false
    }
    
    
    //下载
    override func downloaderData()
    {
        //进入加载状态
        ProgressHUD.showOnView(view)
        
        var urlString = String(format: kLimitUrl, curPage)
        
        if cateId != nil{
            //有分类
            urlString = urlString.stringByAppendingString("&category_id=\(cateId!)")
        }
        
        let LFDown = LFDownloader()
        LFDown.delegate = self
        LFDown.downloadWithURLString(urlString)
    }
    
    
//MARK:表格的方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 100
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellId = "limitCellId"
        var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? LimitCell
        if cell == nil
        {
            cell = NSBundle.mainBundle().loadNibNamed("LimitCell", owner: nil, options: nil).last as? LimitCell
            cell?.selectionStyle = .None
        }
        
        let model = dataArray[indexPath.row]
        cell?.config(model as! LimitModel, atindex: indexPath.row + 1)
        return cell!
    }
    
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        //点击跳转详情界面
        let detailVC = DetailViewController()
        
        let model = dataArray[indexPath.row] as! LimitModel
        detailVC.appId = model.applicationId
        //跳转之前隐藏Tabbar
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(detailVC, animated: true)
        //跳转之后前面界面显示tabBar
        self.hidesBottomBarWhenPushed = false
    }
    
}


//MARK: LFDownloaderDelegate代理方法
extension LimitFreeViewController : LFDownloaderDelegate
{
    //请求失败
    func downloader(downloader: LFDownloader, didFailWithError error: NSError) {
         ProgressHUD.hideAfterFailOnView(view)
        print(error)
    }
    
    //请求成功
    func downloader(downloader: LFDownloader, didFinishWithData data: NSData) {
        
        //JSON解析
//        let str = NSString(data: data, encoding: NSUTF8StringEncoding)
//        print(str!)
        
        //这段代码应该写在下载结束的地方--begin
        if curPage == 1
        {
            //清空数组
            dataArray.removeAllObjects()
        }
        //这段代码应该写在下载结束的地方--end
        
        let result = try!
        NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
        if result.isKindOfClass(NSDictionary)
        {
            let dict = result as! Dictionary<String, AnyObject>
            let array = dict["applications"] as! Array<Dictionary<String,AnyObject>>
            for appDict in array
            {
                let model = LimitModel()
                //使用KVC来解析
                model.setValuesForKeysWithDictionary(appDict)
                dataArray.addObject(model)
            }
            
        }
        
        dispatch_async(dispatch_get_main_queue(),{
            
            self.tableView!.reloadData()
            
            //结束刷新
            self.tableView?.headerView?.endRefreshing()
            self.tableView?.footerView?.endRefreshing()
//                        NSThread.sleepForTimeInterval(5)
            ProgressHUD.hideAfterSuccessOnView(self.view)
            
            })
    }
}

extension LimitFreeViewController : CategoryViewControllerDelegate
{
    func didClickCateId(cateId: String, cateName: String) {
        //1.标题文字
        var title = "限免-"+cateName
        if cateName == "全部"
        {
            title = "限免"
        }
        addnavTitle(title)
        //2.重新下载数据
        self.cateId = cateId
        curPage = 1
        downloaderData()
    }
}


